<template>
	<div class="login-container">
		<video class="video"
			muted
			src="../../assets/video/bg-video.mp4"
			loop="loop"
			autoplay="true"></video>
		<div class="bg2"></div>
		<!-- 常规登入 -->
		<el-form :model="loginForm"
			status-icon
			:rules="rules"
			ref="loginForm"
			label-width="100px"
			class="login-loginForm">
			<h1 class="title">管理系统</h1>
			<i @click="isErweiLogin = !isErweiLogin"
				:class="[
          'jiaobiao',
          'iconfont',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"></i>
			<div class="common-login"
				v-if="!isErweiLogin">
				<el-form-item label="用户名"
					prop="username">
					<el-input type="text"
						v-model="loginForm.username"
						autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="密码"
					prop="password">
					<el-input type="password"
						v-model="loginForm.password"
						autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="验证码"
					prop="captcha">
					<el-input maxlength="5"
						v-model="loginForm.captcha"
						class="captcha"
						ref="captcha"
						@keydown.native.enter="submitForm('loginForm')"></el-input>
					<span @click="updateCaptcha"
						class="captcha-svg"
						v-html="captchaSvg"></span>
				</el-form-item>

				<el-form-item>
					<el-button type="primary"
						@click="submitForm('loginForm')">提交</el-button>
				</el-form-item>
			</div>
			<!-- 切换二维码登入 -->
			<div class="erwei"
				v-else>
				<div class="img">
					<img :src="qrDataUrl"
						width="200px"
						alt="" />
					<i class="mask"
						:style="qrStyle"
						@click="getQrcode"
						v-show="isScanCodeSuccess">
					</i>
				</div>
				<p v-text="qrtip">请使用手机微信扫码登入</p>
			</div>
		</el-form>
	</div>
</template>
<script>
	//引入api中的方法
	import * as api from "../../api";
	import { mapMutations } from "vuex";
	//引入socket.io
	//引入生成二维码的插件qrcode
	import io from "socket.io-client";
	import qrcode from "qrcode";
	//引入扫码成功和失效的图片
	import codeSuccessImg from "../../assets/img/scancode.png";
	import codeInvalidImg from "@/assets/img/invalidQr.png";
	var validateCaptcha = (rule, value, callback) => {
		//callback只要传参了,表示表单验证不通过,不传参表示表单验证通过
		//value就是在input中的输入值
		//rule是个对象,就是验证对象
		if (value.length !== 5) {
			callback("验证码必须是5位");
		} else {
			callback();
		}
	};
	var validateUsername = (rule, value, callback) => {
		//callback只要传参了,表示表单验证不通过,不传参表示表单验证通过
		//value就是在input中的输入值
		//rule是个对象,就是验证对象
		var reg = /^\w{3,12}$/;

		if (reg.test(value)) {
			//验证通过
			callback();
		} else {
			callback("用户名可以是字母数字下划线,3-12位");
		}
	};
	var validatePass = (rule, value, callback) => {
		//callback只要传参了,表示表单验证不通过,不传参表示表单验证通过
		//value就是在input中的输入值
		//rule是个对象,就是验证对象
		if (value.length < 3) {
			callback("密码长度不能小于3位");
		} else {
			callback();
		}
	};
	export default {
		data() {
			return {
				isErweiLogin: false, //是否是二维码登入
				captchaSvg: "", //验证码svg
				qrtip:"",//切换到二维码登入时的提示文字
				loginForm: {
					//登入输入框的数据
					username: "",
					password: "",
					captcha: "",
				},
				rules: {
					//表单验证规则
					username: [{ validator: validateUsername, trigger: "blur" }],
					password: [{ validator: validatePass, trigger: "blur" }],
					captcha: [{ validator: validateCaptcha, trigger: "blur" }],
				},
				qrDataUrl: "", //二维码base64的图片地址
				isScanCodeSuccess: false, //是否扫码成功
				qrStyle: {
					backgroundImage: `url(${codeSuccessImg})`,
				},
			};
		},
		created() {
			//调用获取验证码的方法
			// console.log(process.env.VUE_APP_BASE_URL);
			this.updateCaptcha();
		},
		methods: {
			//封装一个获取二维码地址的方法
			getQrcode() {
				
				//关掉qrcode的遮罩
				this.isScanCodeSuccess = false;
				//让遮罩的样式初始化
				this.qrStyle.backgroundImage = `url(${codeSuccessImg})`
				//从本地取出sid
				let sid = localStorage.getItem("qf-sid");
				if (!sid) {
					this.$message.error("没有sid");
					return;
				}
				api.getQrcodeUrlApi(sid).then((res) => {
					//更改qrtip的提示
					this.qrtip="请使用手机微信扫码登入"
					// console.log(res);
					let qrUrl = res.data.scanCodeUrl;
					//3.通过qrcode将二维码地址生成二维码
					qrcode.toDataURL(qrUrl, (err, dataUrl) => {
						// console.log(dataUrl);
						this.qrDataUrl = dataUrl;
					});
				});
			},
			...mapMutations(["SET_USER_INFO"]),
			//封装一个方法,专门用于获取验证码
			updateCaptcha() {
				api.getCaptchaApi().then((res) => {
					// console.log(res.data);
					this.captchaSvg = res.data.img;
				});
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					//所有的表单校验通过之后,那么valid的值是true
					//不然valid的布尔值就是false

					//1.先校验本地的表单是否通过
					//2.校验验证码是否正确
					//3.校验用户名密码是否正确

					if (valid) {
						//表单校验通过了
						//打开Loading动画
						const loading = this.$loading({
							lock: true,
							text: "正在登入...",
							spinner: "iconfont icon-jiazaizhong",
							background: "rgba(0, 0, 0, 0.7)",
						});
						//校验验证码 验证码都是小写,所以把用户传入的通通转成小写
						api.verifyCaptcha(this.loginForm.captcha.toLowerCase()).then((res) => {
							// console.log(res)
							if (res.data.state) {
								//验证码通过
								//继续校验用户名和用户密码
								api
									.loginApi(this.loginForm.username, this.loginForm.password)
									.then((res) => {
										// console.log(res.data)
										if (res.data.state) {
											loading.close(); //关闭加载动画
											this.$message.success({
												message: "登入成功,正在跳转...",
												type: "success",
												duration: 1000,
											});
											//登入成功
											//1.将token储存到本地
											localStorage.setItem("qf-token", res.data.token);
											//2.将userInfo存到本地
											localStorage.setItem(
												"qf-userInfo",
												JSON.stringify(res.data.userInfo)
											);
											//按钮权限
											//按钮权限
											localStorage.setItem("permissionButtons", JSON.stringify(res.data.permission.buttons))
											//3.将用户信息添加到vuex
											this.SET_USER_INFO(res.data.userInfo);
											//4.跳转到主页
											this.$router.push("/");
										} else {
											//登入失败,用户名或者密码错误
											// alert("账户或者密码错误")
											loading.close(); //关闭加载动画
											//this.$message.error("账号或者密码错误");
										}
									});
							} else {
								// console.log('验证码错误');
								loading.close(); //关闭加载动画
								//this.$message.error("验证码错误");
								//清空验证码输入框的内容
								this.loginForm.captcha = "";
								//让输入框获得焦点
								this.$refs.captcha.focus();
								//验证码错误,刷新验证码
								this.updateCaptcha();
							}
						});
					} else {
						//表单校验不通过
						console.log("error submit!!");
						return false;
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
		},
		watch: {
			//监听切换二维码登入的字段
			isErweiLogin(newVal, oldVal) {
				if (newVal) {
					//已经切换成了二维码登入
					//1.通过socket.io和服务器建立socket连接
					let socket = io("wss://chst.vip");
					//2.监听socket连接成功事件,发送请求,请求"/users/getScancode"获取二维码地址;
					socket.on("connectSuccess", (data) => {
						// console.log(data);
						//将sid存到本地
						let { sid } = data;
						localStorage.setItem("qf-sid", sid);
						//3.获取二维码地址,并且声称二维码图片
						this.getQrcode();
					});

					//4.用户扫描二维码
					//5.监听socket事件 scancodeSuccess(这个事件不是socket.io定义的,是前后端约定的),获取到wechatCode
					socket.on("scancodeSuccess", (data) => {
						// console.log('扫码成功');
						// console.log(data);
						//6.请求users/wechatLogin,传递wechatCode
						if (data.state) {
							//扫码成功

							//显示遮罩
							this.isScanCodeSuccess = true;
							api.wechatLoginApi(data.wechatCode).then((res) => {
								if (res.data.state) {
									//登入成功
									console.log(res);
									//将用户信息和token储存起来
									//1.将token储存到本地
									localStorage.setItem("qf-token", res.data.token);
									//2.将userInfo存到本地
									localStorage.setItem("qf-userInfo", JSON.stringify(res.data.userInfo));
									//3.将用户信息保存到vuex
									this.SET_USER_INFO(res.data.userInfo);
									//按钮权限
									localStorage.setItem("permissionButtons", JSON.stringify(res.data.permission.buttons))
									//4.跳转到首页
									this.$router.push("/");
								} else {
									//登入失败
									this.$message.error("微信登入失败");
								}
							});
						} else {
							//提示扫码失败
							this.$message.error("扫码失败");
						}
						//7.判断成功和失败
					});

					socket.on("invalidCode", (data) => {
						console.log(data);
						this.qrStyle.backgroundImage = `url(${codeInvalidImg})`; //显示二维码失效的标志
						this.isScanCodeSuccess = true; //显示遮罩
						this.qrtip="二维码失效,请点击刷新二维码"

					});
				} else {
					//切换成了普通登入
					//二维码遮罩关闭
					this.isScanCodeSuccess = false;
				}
			},
		},
	};
</script>
<style scoped lang="less">
//样式设置不上的情况,解决方案
//1.检查类名是否正确
//2.检查权重是否正确
//3.检查是否需要穿透

.login-container {
	text-align: center;
	color: #fff;
	.common-login {
		padding-right: 50px;
	}
	//二维码样式
	.erwei .img {
		display: inline-block;
		position: relative;
		width: 200px;
		height: 200px;
		img {
			position: absolute;
			left: 0;
		}
		.mask {
			width: 100%;
			height: 100%;
			opacity: 0.8;
			background-color: #fff;
			position: absolute;
			left: 0;
			// background-image: url("../../assets/img/scancode.png");
			background-size: 50%;
			background-repeat: no-repeat;
			background-position: center;
			cursor: pointer;
		}
	}
	.jiaobiao {
		font-size: 60px;
		color: #fff;
		position: absolute;
		right: -1px;
		top: -1px;
		cursor: pointer;
		opacity: 0.7;
	}
	.video {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}
	.bg2 {
		background-image: url("../../assets/img/bg2.png");
		background-repeat: no-repeat;
		position: fixed;
		width: 20%;
		height: 40%;
		background-size: 100% 100%;
		left: 20%;
		top: 40%;
		opacity: 0.5;
	}
	.el-form {
		position: fixed;
		right: 10%;
		top: 25%;
		border-radius: 5px;
		width: 400px;
		background-color: rgba(0, 0, 0, 0.3);
		padding: 100px 0 50px 0;
		/deep/ .el-input__inner {
			width: 250px;
		}
		/deep/ .el-button--primary {
			background: linear-gradient(90deg, #1596fb, #002dff);
			width: 250px;
		}
		/deep/ .el-form-item__label {
			color: #fff;
		}
		.title {
			margin: 0 0 60px 0;
			text-align: center;
			color: #fff;
		}
		/deep/ .captcha {
			width: 100px;
			vertical-align: top;
			.el-input__inner {
				width: 100%;
				height: 45px;
				border-radius: 5px 0 0 5px;
				border: 0;
				font-size: 18px;
			}
		}
		svg path {
			stroke: red;
		}
		.captcha-svg {
			background: #fff;
			display: inline-block;
			height: 45px;
			width: 150px;
			text-align: center;
			cursor: pointer;
			border: 0;
			border-radius: 0px 5px 5px 0;
		}
		.el-form-item__content {
			width: 250px !important;
		}
	}
}
</style>
